//
//  MDPreviewImageViewController.swift
//  MDSolveWorries
//
//  Created by Alan on 2018/1/5.
//  Copyright © 2018年 MD. All rights reserved.
//

import UIKit
import SDWebImage


let MainWidth = UIScreen.main.bounds.size.width
let MainHeight = UIScreen.main.bounds.size.height

public class MDPreviewImageViewController: UIViewController {

    private var imageArray:[MDPreviewImageModel]? //图片数组
    private var index:Int? //索引
    
    //UIPageControl
    lazy private var pageControl:UIPageControl  = {
        let pageControl = UIPageControl()
        pageControl.center = CGPoint(x: MainWidth/2,
                                      y: MainHeight - 30)   //设置位置为屏幕底部
        pageControl.isUserInteractionEnabled = false
        self.view.addSubview(pageControl)
        return pageControl
    }()
    
    //UICollectionViewFlowLayout
    lazy private var collectionViewLayout:UICollectionViewFlowLayout = {
        let collectionViewLayout = UICollectionViewFlowLayout()
        collectionViewLayout.minimumLineSpacing = 0
        collectionViewLayout.minimumInteritemSpacing = 0
        //横向滚动
        collectionViewLayout.scrollDirection = .horizontal
        return collectionViewLayout
    }()
    
    //UICollectionView
    lazy private var collectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: self.view.bounds,
                                          collectionViewLayout: collectionViewLayout)
        collectionView.backgroundColor = UIColor.black
        collectionView.register(MDImagePreviewCell.self, forCellWithReuseIdentifier: "MDImagePreviewCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        self.view.addSubview(collectionView)
        return collectionView
    }()
    
    
    public init(images:[MDPreviewImageModel],index:Int = 0) {
        self.imageArray = images
        self.index = index
        super.init(nibName: nil, bundle: nil)
    }
    
    public required  init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.automaticallyAdjustsScrollViewInsets = false
        //将视图滚动到默认图片上
        let indexPath = IndexPath(item: index!, section: 0)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        
        pageControl.numberOfPages = imageArray!.count
        pageControl.currentPage = index!
        
        // Do any additional setup after loading the view.
    }
    
    override public var prefersStatusBarHidden: Bool{
        return true
    }
    
    override public func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        UIApplication.shared.isStatusBarHidden  =  true
    }
    override public func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: false)
        UIApplication.shared.isStatusBarHidden  =  false
    }
    
    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


extension MDPreviewImageViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (self.imageArray?.count)!
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MDImagePreviewCell",
                                                      for: indexPath) as! MDImagePreviewCell
        let model = self.imageArray![indexPath.item]
        if model.type == .defaut{
            cell.imageView.image = model.image!
        }else{
            cell.play()
            cell.imageView.sd_setImage(with: URL.init(string: model.url!), completed: { (image, err, type, url) in
                cell.stop()
            })
        }
        return cell
    }
    
    //collectionView单元格尺寸
    public func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        return self.view.bounds.size
    }
    
    //collectionView里某个cell将要显示
    public func collectionView(_ collectionView: UICollectionView,
                        willDisplay cell: UICollectionViewCell,
                        forItemAt indexPath: IndexPath) {
        if let cell = cell as? MDImagePreviewCell{
            //由于单元格是复用的，所以要重置内部元素尺寸
            cell.resetSize()
        }
    }
    
    //collectionView里某个cell显示完毕
    public func collectionView(_ collectionView: UICollectionView,
                        didEndDisplaying cell: UICollectionViewCell,
                        forItemAt indexPath: IndexPath) {
        //当前显示的单元格
        let visibleCell = collectionView.visibleCells[0]
        //设置页控制器当前页
        self.pageControl.currentPage = collectionView.indexPath(for: visibleCell)!.item
    }
    
    
}

